<template>
  <div class="latestMsgContainer">
    <user-chat :styleChat="chatStyle" :chatNow="list" @playChange="playa"></user-chat>
    <div class="msgBtn">
      <div @touchend="stop" @touchstart="start" class="voice">
          <yd-icon name="speak"  custom slot="icon" size=".5rem" style="position:absolute;z-index:1"></yd-icon>
      </div>
      <textarea type="text" class="msg" v-model="msg" style="font-size:14px;font-family:'MicrosoftYaHei';"></textarea>
      <button @touchend="sendMsg" class="send">发送</button>
      <button class="add" @click="othershow=!othershow">其他</button>
      <!-- <input type="file" ref="file"> -->
      <div class="other" v-show="othershow">
          <button @touchend="myCamera()">拍照</button>
          <button @touchend="myGallery()">相册</button>
          <!-- <button @touchend="sendFile">发送图片音频</button>         -->
      </div>
    </div>
    <!-- <audio :src="audio"> -->
    <!-- 您的浏览器不支持 audio 标签。 -->
    <!-- </audio> -->
  </div>
</template>
<script>
  import userChat from "@/components/userChat"
  import {vun} from "@/common/js/base/mysocket.js";
  // import base64 from '@/common/js/base/camera.js'
  import myAudio from "@/common/js/base/chatAudio.js"
  import {getDate} from '@/common/js/base/time.js'
  export default {
    data(){
      return{
        chatStyle:{//聊天界面样式
          bgImage:'',
          bgColor:'',
        },
        othershow:false,
        myFile:'',
        msg:'',
        list:[],
        mybase:null,
        time:null,
        ip:this.$store.state.ip,
        audio:'',//录音路径
      }
    },
    computed:{
      // msgImg(){
      //   return this.$store.state.mgsUrl
      // },
      msgText(){
        return this.$store.state.msgText
      },
      socketStatus(){
         return this.$store.state.socketStatus
      },
      sendstatus(){
        return this.$store.state.sendstatus
      }
    },
    watch:{
      // msgImg(newVal,oldVal){
      //  let newMsg=JSON.parse(newVal)
      // //  console.log(newMsg)
      //   if(newVal!=null){//判断是否将消息已经置空
      //      let a= {
      //       img: "http://img1.shikee.com/try/2016/06/23/14381920926024616259.jpg",
      //       pic:newVal,
      //         time:'2017-1-1'
      //       };
      //     this.list.push(a)
      //   }
      // },
      socketStatus(newVal,oldVal){//监听socket变化
        // console.log(newVal)
          vun.getMsg()
      },
      sendstatus(newVal,oldVal){//监听发送状态
         if(newVal==0){//发送成功判断
            this.myFile=null;
            this.$store.commit("sendstatus",1)
         }
      },
      msgText(newVal,oldVal){//监听消息
        var that=this;
        that.myTime()
         if(newVal!=null){//判断是否将消息已经置空
            let newMsg=newVal
            console.log(newMsg)
            let data={
                userId:newMsg.userId//好友ID
            }
            this.ylAjax.searchFriendbyId(data)
                       .then(res=>{
                         if(res.state==0){
                           if(newMsg.chatType=="null"&&newMsg.msgContent!=="null"){//文字消息
                                let a= {
                                    img: res.data.photo,//头像
                                    msg:newMsg.msgContent,//消息
                                    time:that.time,//时间
                                    userName:newMsg.userName,//用户名
                                    userId:newMsg.userId,//ID
                                  };
                                  this.list.push(a)
                           }else if(newMsg.path!=="null"&&newMsg.chatType=="jpeg"){//图片
                                  let a={
                                      img: res.data.photo,//头像
                                      pic:this.ip+newMsg.path,//消息
                                      time:that.time,//时间
                                      userName:newMsg.userName,//用户名
                                      userId:newMsg.userId,//ID
                                  }
                                  this.list.push(a)
                           }else if(newMsg.path!=="null"&&newMsg.chatType=="amr"){//语音
                                  let a={
                                      img: res.data.photo,//头像
                                      amr:this.ip+newMsg.path,//消息
                                      time:that.time,//时间
                                      userName:newMsg.userName,//用户名
                                      userId:newMsg.userId,//ID
                                      play:false,
                                  }
                                    // myAudio.startPlay(a.amr)
                                    //   var p=this.$store.state.auobj;
                                    //   p.s.play(()=>{
                                    //     console.log("成功")
                                    //     console.log(p.r)
                                    //     a.play=true;
                                    //       console.log(this.chatNow[index].amr)
                                     
                                    //   })
                                this.list.push(a)
                           }
                         }
                       })
          //  console.log(newMsg)
         }
      },
      mybase(newVal,oldVal){
        // alert(newVal)
        // this.myFile=this.toblob(newVal)
      }
    },
    methods:{
        playa(index){//修改播放状态
        this.list[index].play=true
        // localStorage.setItem("chat_"+localStorage.userid,JSON.stringify(this.list))
        localStorage.chat=JSON.stringify(this.list)
        console.log(1)
      },
       myTime(){//获取系统时间
        let timeNow=getDate(Date.now())
        this.time=timeNow.hours+":"+timeNow.minutes+":"+timeNow.second
      },
      toblob(dataurl){//base64转blob
           var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
      },
      start(){
        myAudio.startReady()
      },
      stop(){
        myAudio.stopReady();
        setTimeout(() => {
             this.mybase=this.$store.state.base64;
            this.myFile=this.toblob(this.mybase)
            console.log(this.myFile)
            this.sendFile()
        }, 500);

      },
      sendMsg(){//发送消息
        if(this.msg!=""){
            var msg = {
                msgContent:this.msg,//发送内容
                postsId:localStorage.userid
            };
            // console.log(msg)
            vun.sendText(msg)
            this.msg=""
        }
      },
      sendFile(){//发送图片
        if(this.myFile!=null){
           vun.sendFile(this.myFile)
        }else{

        }
      },
      compressImage(url){
        let that=this
        that.$store.commit("myzip",null)//先清空保存压缩文件变量
          plus.zip.compressImage({
              src:url,
              dst:"_doc/a.jpg",
              quality:20,
              overwrite:true
            },
            function(e) {
              // console.log(e.target)
              that.$store.commit("myzip",e.target)
              console.log("Compress success!");
            },function(error) {
              console.log("Compress error!");
          });
        },
    myCamera(){//调用手机拍照
      var that=this
      if(window.plus){
          plusReady();
        }else{
          document.addEventListener("plusready",plusReady,false);
        }
        var cmr = plus.camera.getCamera();
        var res = cmr.supportedImageResolutions[0];
        var fmt = cmr.supportedImageFormats[0];
          cmr.captureImage( function( path ){
            that.compressImage(path)
            setTimeout(()=> {
              if(that.$store.state.myzip!=null){
                 let mypath=that.$store.state.myzip
                    plus.io.resolveLocalFileSystemURL(mypath,function(entry){
                    entry.file(function (file) {
                      let fileReader = new plus.io.FileReader();
                      fileReader.readAsDataURL(file);
                      fileReader.onloadend = function (p) {
                        that.mybase = p.target.result.toString();
                        that.myFile=that.toblob(that.mybase)
                        // console.log(that.myFile)
                              setTimeout(()=>{
                                    that.sendFile()
                                    that.othershow=false
                              },200)                        
                      }
                    })
                })
              }else{//如果为空则提示

              }
            }, 1000);
            },
          function( error ) {
               that.cropShow=false
               that.crop=false
              console.log( "取消拍照" );
          },
          {resolution:res,format:fmt}
        );
    },
    myGallery(){//手机相册
          let that=this;
          that.photoType=2
           plus.gallery.pick( function(path){
                 that.compressImage(path)
                  setTimeout(()=> {//压缩处理图片
                          let mypath=that.$store.state.myzip
                          plus.io.resolveLocalFileSystemURL(mypath,function(entry){
                          entry.file(function (file) {//转base64
                            let fileReader = new plus.io.FileReader();
                            fileReader.readAsDataURL(file);
                            fileReader.onloadend = function (p) {
                              that.mybase = p.target.result.toString();
                              that.myFile=that.toblob(that.mybase)//转BLOB
                              // console.log(that.myFile)
                              setTimeout(()=>{
                                    that.sendFile()
                                     that.othershow=false
                              },200)                               
                            }
                          })
                      })
                  }, 1000);
            }, function ( e ) {
              that.cropShow=false
                  that.crop=false
              console.log( "取消选择图片" );
            }, {filter:"image"} );
    },
    },
    components:{
      userChat
    },
    mounted(){
      vun.getMsg()
    //test:
      // if(localStorage.getItem("chat_"+localStorage.userid)){
      //   // this.list= JSON.parse(localStorage.getItem("chat_"+localStorage.userid))
      //   this.list=JSON.parse(localStorage.chat)
      // } 
     if(localStorage.chat){
        this.list=JSON.parse(localStorage.chat)
      }
    // var blob = this.toblob('data:text/plain;base64,YWFhYWFhYQ==');
    //  console.log(myAudio.stopReady)
    },
    activated(){
      // if(localStorage.getItem("chat_"+localStorage.userid)){
      //   this.list= JSON.parse(localStorage.getItem("chat_"+localStorage.userid))
      // }
      if(localStorage.chat){
        this.list=JSON.parse(localStorage.chat)
      }
    }
  }
</script>
<style lang="less" scoped>
@import "~less/base";
  .msgBtn{
    position: fixed;
    bottom: 0;
    width: 100%;
    min-height: 1.2rem;
    // max-height: 2rem;
    z-index: 100;
    background-color: #eee;
    padding-top: .1rem;
    .voice{//录音
      line-height: .8rem;
      width:10% ;
      height: .8rem;
      display: inline-block;
      padding-left: .15rem;
      border-radius: 5px;
    }
    .voice:active,.send:active,.add:active{
      background-color: @background-a;
    }
    .msg{//输入框
      height:.8rem;
      width:70%;
      // margin-left: 10%;
      border: 1px solid @color-border4;
      background-color: #ffffff;
      line-height: .5rem;
      padding: .1rem;
      border-radius: 5px;
      letter-spacing: 2px;
    }
    .send{//发送
      // background-color: #eeeeee;
      border: none;
      height: .8rem;
      position: absolute;
      left:81%;
      border-radius: 5px;
      width: .8rem;
      text-align: center;
    }
    .add{
      border: none;
      height: .8rem;
      position: absolute;
      left:90%;
      border-radius: 5px;
      width: .8rem;
      text-align: center;      
    }
    .other{
      width:80%;
      text-align: center;
      margin-left: 5%;
      button{
        margin: .1rem;
        width: 2rem;
        height: .8rem;
        border:  1px solid @color-border4;
        font-size: 16px;
      }
      button:active{
        background-color: @background-a; 
        color: #ffffff;       
      }
    }
  }
</style>
